package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

//进店客户
@RestController
@Slf4j
public class UserController {

    @Autowired
    private HttpSession session;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private UserService userService;

    //发送短信验证码
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String,String> map){
        //1 接收参数
        String phone = map.get("phone");

        //2生成验证码
        //String code = RandomUtil.randomNumbers(6);
        String code = "123";
        log.info("生成的验证码为：{}",code);

        //3 将验证码保存到session中
        session.setAttribute("SMS_" + phone,code);

        //4 发送验证码到手机
        //smsTemplate.sendSms(phone,code);
        return ResultInfo.success(null);


    }

    //用户登录注册
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //1接收参数
        String phone = map.get("phone");
        String code = map.get("code");

        //2 校验code 前端传入code VS session保存到code
        String codeFromSession = (String) session.getAttribute("SMS_" + phone);
        if (! StringUtils.equals(code,codeFromSession)
                ||StringUtils.isEmpty(code)
                || StringUtils.isEmpty(codeFromSession)
        ) {
            return ResultInfo.error("验证码不正确");
        }
        //3 根据phone从数据库中查询
        User user = userService.findByPhone(phone);
        if (user != null){
            //查到了 代表的是老用户在登录

        }else{
            //没有查到 说明是新用户在注册
            user = new User();

            user.setPhone(phone);
            user.setStatus(1);//激活用户
            userService.save(user);

        }

        //4 将user信息保存到session中(注意： 这个键必须跟拦截器中使用发键一致)
        session.setAttribute("SESSION_USER",user);

        //5 返回成功的标识 (注意不要忘记返回user 前端需要使用)
        return ResultInfo.success(user);
    }

    //退出
    @PostMapping("/user/logout")
    public ResultInfo logout(){
        session.invalidate();
        return ResultInfo.success(null);
    }

}
